import CryptoJS from 'crypto-js';

// 密钥长度
const DEFAULT_KEY_LENGTH = 16;

/**
 * aes方式加密数据
 * @param data 需加密数据
 * @param key 密钥key值
 * @returns {string} 加密后的字符
 */
export function aesEncryptData (data, key) {
  const keyBytes = concatKey(key);
  let words = [];
  for (let i = 0; i < keyBytes.length; i++) {
    words[i >>> 2] |= (keyBytes[i] & 0xff) << (24 - (i % 4) * 8);
  }
  const parseData = CryptoJS.enc.Utf8.parse(data);
  // eslint-disable-next-line new-cap
  const encrypted = CryptoJS.AES.encrypt(parseData, new CryptoJS.lib.WordArray.init(words, keyBytes.length), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}

/**
 * aes方式解密数据
 * @param data 需解密的数据
 * @param key 密钥key值
 * @returns {string} 解密后的字符
 */
export function aesDecryptData (data, key) {
  const keyBytes = concatKey(key);
  let words = [];
  for (let i = 0; i < keyBytes.length; i++) {
    words[i >>> 2] |= (keyBytes[i] & 0xff) << (24 - (i % 4) * 8);
  }
  // eslint-disable-next-line new-cap
  const decryptData = CryptoJS.AES.decrypt(data, new CryptoJS.lib.WordArray.init(words, keyBytes.length), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decryptData).toString();
}

/**
 * 处理字符串长度为16位
 * @param key 字符串
 * @returns {[]|*[]} byte类型数组
 */
function concatKey (key) {
  if (key === null || key.length === DEFAULT_KEY_LENGTH) {
    return stringToByte(key);
  }

  if (key.length > DEFAULT_KEY_LENGTH) {
    key = key.substring(0, DEFAULT_KEY_LENGTH);
    return stringToByte(key);
  } else {
    let bytes = [];
    const keyByte = stringToByte(key);
    for (let i = 0; i < keyByte.length; i++) {
      bytes[i] = keyByte[i];
    }
    for (let i = keyByte.length; i < DEFAULT_KEY_LENGTH; i++) {
      bytes[i] = DEFAULT_KEY_LENGTH - key.length;
    }
    return bytes;
  }
}

/**
 * 字符串转换位byte[]
 * @param str 转换字符
 * @returns {[]} byte数组
 */
function stringToByte (str) {
  const bytes = [];
  if (str === null) {
    return bytes;
  }
  let idx = '';
  for (let i = 0; i < str.length; i++) {
    idx = str.charCodeAt(i);
    if (idx & 0xff00) {
      bytes.push(idx >> 8);
      bytes.push(idx & 0xff);
    } else {
      bytes.push(idx);
    }
  }
  return bytes;
}
